﻿using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using SelfService.Model;
using SelfService.Model.Interface;
using SelfService.Model.Models;
using WalkingTec.Mvvm.Core;

namespace SelfService.Tasks;

[Display(Name = "自动冲正")]
public class AddCreditTask : BaseTask
{
    private readonly IServiceProvider _provider;
    public AddCreditTask(WTMContext context, IServiceProvider provider) : base(context)
    {
        _provider = provider;
    }
    
    public override async Task<bool> Process()
    {
        this.Logger("查询支付结果", ActionLogTypesEnum.Job);
        try
        {
            //调用支付接口
            IHisOrder service;
            try
            {
                var scope = _provider.CreateScope();
                service = scope.ServiceProvider.GetRequiredService<IHisOrder>();
            }
            catch (Exception)
            {
                this.Logger($"没有启用HisOrder服务", ActionLogTypesEnum.Exception);
                return false;
            }
            if (service == null)
            {
                this.Logger($"没有启用HisOrder服务", ActionLogTypesEnum.Exception);
                return false;
            }
            var dc = Context.DC;
            var list = await dc.Set<SysPay>()
                .Where(e => 
                    e.PayStatus == PayStatusEnum.支付成功 && 
                    e.Use == PayUseEnum.门诊充值 && 
                    e.UseStatus == UseStatusEnum.未知 && 
                    e.RefundStatus == RefundStatusEnum.未发起 &&
                    e.UpdateTime < DateTime.Now.AddMinutes(-5))
                .Include(e => e.Patient)
                .Include(e => e.PayType)
                .ToListAsync();
            foreach (var element in list)
            {
                var result = await service.AddCredit(element, element.Patient);
                if (result.Code == 200)
                {
                    element.UseStatus = UseStatusEnum.成功;
                    element.UpdateTime = DateTime.Now;
                    this.Logger($"订单[{element.OutOrderNo}]充值成功", ActionLogTypesEnum.Job);
                }
                else
                {
                    element.UseStatus = UseStatusEnum.失败;
                    element.UpdateTime = DateTime.Now;
                    this.Logger($"订单[{element.OutOrderNo}]充值失败, {result.Message}", ActionLogTypesEnum.Exception);
                }
                await dc.SaveChangesAsync();
            }
            if (list.Count == 0)
            {
                this.Logger("没有待冲正支付", ActionLogTypesEnum.Job);
            }
            return true;
        }
        catch (Exception e)
        {
            this.Logger($"自动充值服务发生异常, {e.Message}. {e.StackTrace} | {e.InnerException}", ActionLogTypesEnum.Exception);
        }
        return false;
    }
}